package GachNo;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
 
/**
 * @author TRUNG
 */
public class GachNo extends MIDlet implements CommandListener, HTTPInterface, ItemCommandListener, Runnable, ItemStateListener {
    private Display     display;
    private Displayable currentform;
    private Displayable previousForm;
    private HTTPconnect myConnection;       
    private Alert       alertInfor;
    private String      AppName      = "Gạch nợ";
    private String      AppVerson    = "121004";
    
    private String LINK_LOGIN       = "http://mobisoft.vn/yp/checkinfo.php?code=%s&ma_nv=%s";//http://hcm.neo.com.vn:8081/gachno/checkinfo1.php?code=111111111&ma_nv=08.025
    
    //private String LINK_REPORT    = "http://mobisoft.vn/yp/report.php?code=%s&mid=%s&day=%s&page=%s&step=%s";  
    //http://mobisoft.vn/yp/report_by_phieugiao.php?mid=131&langiao=113677&page=1&step=50        
    //http://mobisoft.vn/yp/report.php?mid=131&page=1&step=20&day=01/06/2012&code=123456789
    
    private String LINK_REPORT      = "http://mobisoft.vn/yp/report.php?mid=%s&page=%s&step=%s&day=%s&code=%s"; 
    private String LINK_REPORT_DOT  = "http://mobisoft.vn/yp/report_by_phieugiao.php?mid=%s&langiao=%s&page=%s&step=%s"; 
    private String LINK_REPORT_SEARCH  = "http://mobisoft.vn/yp/search_erase.php?mid=%s&ma_tt=%s&so_dt=%s";

    //http://mobisoft.vn/yp/search_erase.php?mid=131&ma_tt=IS00675265&so_dt=0912562478
    //private String LINK_SEARCH    = "http://mobisoft.vn/yp/search.php?ma_nv=%s&ma_tt=%s"; 
    private String LINK_SEARCH_LIST = "http://mobisoft.vn/yp/search.php?ma_nv=%s&ma_tt=%s&so_tb=%s";     
    private String LINK_GACHNO      = "http://mobisoft.vn/yp/putinfo.php?code=%s&hdid=%s&PayID=%s&mid=%s"; 
    
    //private String LINK_CLIENT_LIST = "http://mobisoft.vn/yp/getListCustomer.php?mid=%s&page=%s&step=%s";
    //http://mobisoft.vn/yp/getListCustomer.php?m_id=131&page=1&step=20&langiao=113677
    //http://mobisoft.vn/yp/getListCustomer.php?m_id=131&page=1&step=20
    private String LINK_CLIENT_LIST = "http://mobisoft.vn/yp/getListCustomer.php?mid=%s&page=%s&step=%s&langiao=%s";
                                      //http://mobisoft.vn/yp/getListCustomer.php?mid=131&page=1&step=100&langiao=132052
    
    private String LINK_PASS_CHANGE = "http://mobisoft.vn/yp/changepass.php?code=%s&mid=%s";//123456789&phone=0985313418&mid=131
    private String LINK_LUOT_GIAO    = "http://mobisoft.vn/yp/getdotphieugiao.php?mid=%s";
    
    private String LINK_HUY_GACHNO  = "http://mobisoft.vn/yp/huygachno.php?pt_id=%s&ng_id=%s"; //http://mobisoft.vn/yp/huygachno.php?pt_id=27241943&ng_id=603
        
    private final int ACTION_LOGIN             = 0;
    private final int ACTION_SEARCH_LIST       = 1;
    private final int ACTION_REPORT_CURRENT    = 2;
    private final int ACTION_REPORT_SETDAY     = 3;
    private final int ACTION_CLIENT_LIST       = 4;
    private final int ACTION_GACH_NO           = 5;
    private final int ACTION_PASS_CHANGE       = 6;
    private final int ACTION_LUOT_GIAO_REPORT   = 7;
    private final int ACTION_GACH_DS           = 8;
    private final int ACTION_REPORT_DOTGIAO    = 9;
    private final int ACTION_HUY_GACH_NO       = 10;
    private final int ACTION_REPORT_SEARCH     = 11;
    private final int ACTION_GACH_DS_LOAD_LIST = 12;
    private final int ACTION_LUOT_GIAO_MAIN    = 13;
    private final int ACTION_ALL_LIST_CLIEN    = 14;
    //private final int ACTION_CLIENTLIST_DOTGIAO= 14;
    
    private final int ACTION_GDS_NOMAL         = -1;
    private final int ACTION_GDS_PENDING       = 0;
    private final int ACTION_GDS_LIST          = 1;
    
    private String link     = "";
    private String phoneNumber = "";
    private String nv_pass  = "123";//ma an toan, <-- doi pass
    private String nv_id    = "08.037";//ma nhan vien    
    private String mid      = "";//nhan vien Id, dc tra ve sau khi dang nhap        
    //Login form
    private Form        formLogin;
    private TextField   L_phone_number, L_user_code;
    private Command     L_login, L_cancel;
    
    //Main form
    private List        formMain;
    private Command     M_menu_exit, 
                        M_menu_report, 
                        M_menu_client, 
                        M_menu_setting, 
                        M_truyvan, 
                        M_menu_dotgiao,
                        M_menu_next,
                        M_menu_last, 
                        M_menu_gachno_ds;
    private DateField   M_dateDateField = new DateField("Ngày tháng:", DateField.DATE);
    private int         M_currentPage   = 1;
    private int         M_recordPerPage = 10;
    private int         M_totalRecord   = 0;
    private int         M_selectedIndex = -1;
    
    //Client form
    private Form        formClient;
    private StringItem  C_string_cid,
                        C_string_name, 
                        C_string_seri, 
                        C_string_address, 
                        C_string_sodt, 
                        C_string_status, 
                        C_string_money, 
                        C_string_date;
    private Command     C_menu_back, C_menu_clear;
    private String      C_hdid,C_payId;
    
    //Report form
    private Form        formReport;
    private Command     R_menu_back, 
                        R_menu_update, 
                        R_menu_select,
                        R_menu_ds_dot,
                        R_menu_huy,
                        R_menu_next,
                        R_menu_search,
                        R_menu_last;
    private ChoiceGroup R_list;
    private DateField   R_dateDateField     = new DateField("Ngày tháng:", DateField.DATE);
    private int         R_currentPage       = 1;
    private int         R_recordPerPage     = 10;    
    private int         R_totalRecord       = 0;
    private String      R_totalMoney        = "";
    private boolean     R_success           = false;
    private Form        formReportDot;
    private Command     Rd_menu_back,  
                        Rd_menu_select,
                        //Rd_menu_huy,
                        Rd_menu_next,
                        Rd_menu_search,
                        Rd_menu_last;
    private ChoiceGroup Rd_list;
    private int         Rd_currentPage       = 1;
    private int         Rd_recordPerPage     = 10;    
    private int         Rd_totalRecord       = 0;
    private String      Rd_totalMoney        = "";
    private String      Rd_Date              = "";
    
    //Setting form
    private Form        formSetting;
    private TextField   S_oldpass;
    private TextField   S_newpass;
    private TextField   S_retype;
    private Command     S_menu_back, S_menu_update, S_menu_reset;   
    private StringItem  S_string_int,S_string_out;
    private StringItem  S_string_imei,S_string_imsi; 
    private int         S_total_out, S_total_in;
    
    //Search form
    private Form        formSearch;
    private TextField   fs_textfield_mathanhtoan;
    private TextField   fs_textfield_sodt;
    private Command     fs_menu_back, fs_menu_ok;
    
    private int         connectType = 0;// 0 login 1: clien 2: report   
    
    //Gach ds form
    private List        formGachDS;
    private Command     ch_menu_back, 
                        ch_menu_ok,
                        ch_menu_next,
                        ch_menu_check_page,
                        ch_menu_check_all,
                        ch_menu_last;    
    private int         ch_total, ch_sucess, ch_fail;
    private Vector      ch_vector_check;
    //private int         ch_total_money;
    private int         ch_currentPage   = 1;
    private int         ch_recordPerPage = 10;
    private int         ch_totalRecord   = 0;
    //private int         ch_total_check   = 0;/** */
    private String      ch_formName = "Gds";
    
    
    //Dot giao form
    private List        formLuotGiao;
    private Command     dg_menu_back, dg_menu_ok;
    private String      dg_luot_giao_id;
    private Displayable dg_next_screen;
    
    //Ket qua gach ds form
    private Form        formGachDsKq;
    private StringItem  kq_string_total,
                        kq_string_success, 
                        kq_string_status, 
                        kq_string_fail;
    private Command     kq_menu_cancel;
    private boolean     kq_menu_status;
             
    
    //Huy gach no form
    private Form        formHuyGachNo;
    private StringItem  H_string_matt, 
                        H_string_name, 
                        H_string_so_dt, 
                        H_string_so_tien, 
                        H_string_ngay_gach, 
                        H_string_trangthai;
    private Command     H_menu_back, H_menu_ok;
    private ReportItem  H_item;
    private Displayable H_previousForm;
    
    //Confirm form
    private Form        formConfirm;
    private StringItem  fc_stringitem_content;
    private Command     fc_menu_cancel, fc_menu_ok;


    
    public class ClientItem{
        public String ma_tt;
        public String ten_khachhang;
        public String so_dt;
        public String so_seri;
        public String tong_tien;
        public String id_hoadon;  
        public String id_payment;
        
        public boolean deptStatus;//da gch nohay chua true = roi
        public int gachds; //-1:bt 1:vao ds gach 0: dang gach
        
        public ClientItem(
                String ma_tt, 
                String ten_khachhang,  
                String so_dt, 
                String so_seri, 
                String tong_tien,
                String id_hoadon,
                String id_payment)
        {
            this.ma_tt        = ma_tt;
            this.ten_khachhang= ten_khachhang;
            this.so_dt        = so_dt;
            this.so_seri      = so_seri;
            this.tong_tien    = tong_tien;
            this.id_hoadon    = id_hoadon;
            this.id_payment   = id_payment;
            
            deptStatus = false;
            gachds = -1;
        }
    }
    
    public class ReportItem{
        //<br/>01446055:MOHAMAD ZEN:28011518:181:07/09/2012:07/09/2012
        public String ma_tt;
        public String ten_khachhang;
        public String sodt;
        public String so_tien;
        public String phieutra;
        public String nguoigachid;
        public String ngay_thanh_toan;  
        public String ngay_hien_tai;         
        public boolean deptStatus;
        
        public ReportItem(
                String ma_tt, 
                String ten_khachhang,
                String sodt,
                String so_tien,
                String phieutra, 
                String nguoigachid, 
                String ngay_thanh_toan,
                String ngay_hien_tai)
        {
            this.ma_tt          = ma_tt;
            this.ten_khachhang  = ten_khachhang;
            this.sodt           = sodt;
            this.so_tien        = so_tien;
            this.phieutra       = phieutra;
            this.nguoigachid    = nguoigachid;
            this.ngay_thanh_toan= ngay_thanh_toan;
            this.ngay_hien_tai  = ngay_hien_tai;          
            deptStatus = true;
        }
    }
    private ClientItem[] listClient;
    private ClientItem[] ch_listClient;
    
    private ReportItem[] listReport;
    private ReportItem[] listReportDot;
    private Image check, uncheck;
    
    //--------------------------------------------------------------------------  
    public GachNo() {
        readSettingRMS(AppVerson);  
        ListImage();
        myConnection = new HTTPconnect();
        myConnection.setInterface(this);
        
        java.util.Date now = new java.util.Date();
        M_dateDateField.setDate(now);
        R_dateDateField.setDate(now);       

//        System.getProperty("microedition.platform");
//        String sim = null;
//        String arrProperty [] = new String []{"com.siemens.IMEI","com.samsung.imei","com.sonyericsson.imei","com.motorola.IMEI","com.nokia.mid.imei","com.nokia.imei","phone.imei","IMEI","com.lge.imei"};
//        //String arrProperty [] = new String []{"com.siemens.IMSI","com.samsung.imsi","com.sonyericsson.imsi","com.motorola.IMSI","com.nokia.mid.imsi","com.nokia.imsi","phone.imsi","IMSI","com.lge.imsi"};
//        for (int i=0; i< arrProperty.length;++i){
//            if (sim ==null)
//                sim = System.getProperty(arrProperty[i]);
//            else break;
//        }
    }
    public void startApp() {
        display = Display.getDisplay(this);
        initLoginForm();
    }
    public void pauseApp() {
        
    }
    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }
    public void run() {
        //throw new UnsupportedOperationException("Not supported yet.");
         S_total_out+=link.toCharArray().length;
         myConnection.getData(link);
    }
    
    private void ListImage(){
        try{
            uncheck = Image.createImage("/img/radio1.png");
            check = Image.createImage("/img/radio2.png");
            //System.out.println("Image ok!");
        }catch(Exception e){
            System.err.println(e.getMessage());
            //System.out.println("Image error!");
        }
    }
    
    public void itemStateChanged(Item item) {
        //throw new UnsupportedOperationException("Not supported yet.");        
    }
    
    private void updateReportList(String ma_tt) {
        for (int i=0; i<listReport.length; i++){
            if (listReport[i].ma_tt.equals(ma_tt)){
                R_list.delete(i);

                ReportItem[] r = new ReportItem[listReport.length-1];
                for (int j=0; j<listReport.length-1; j++){
                    if (j<i){
                        r[j] = listReport[j];
                    }else{
                        r[j] = listReport[j+1];
                    }
                }
                listReport = null;
                listReport = r;
                return;
            }
        }
    }
    
    private void updateStatus(String cId) {
        cId = cId.trim();
        /*for (int i=0; i<listClient.length; i++){
            if (listClient[i].cId.equals(cId)){
                
                listClient[i].cStatus = true;
                System.out.println(listClient[i].cId);
                
                return;
            }
        }*/
        
        for (int i=0; i<listClient.length; i++){
            if (listClient[i].ma_tt.equals(cId)){
                //formMain.delete(i);
                listClient[i].deptStatus = true;
                String s = formMain.getString(i);
                if (s.charAt(0)!='*'){
                    s="*"+s;
                }
                formMain.delete(i);
                formMain.insert(i, s, null);
                System.out.println(listClient[i].ma_tt);         
                return;
            }
        }
    }
    /*
     * Gach no theo danh sach
     */
    private void startGachDs() {
        //lay ds
        //boolean[] list = new boolean[formGachDS.size()];
        //formGachDS.getSelectedFlags(list);
        
        int totalcheck = 0;
        for (int i=0; i< ch_vector_check.size(); i++){
            ClientItem ci = (ClientItem)ch_vector_check.elementAt(i);
            if (ci.gachds==ACTION_GDS_LIST) {
                totalcheck++;
            }
        }
        
        kq_menu_status = true;
        startConnect(ACTION_GACH_DS);  
        System.out.println("totalcheck:"+ totalcheck);
        ch_total = totalcheck; 
        ch_sucess = 0; 
        ch_fail = 0;       
    }
    
    private void updateStatusDs(boolean  result) {
       for (int i=0; i< ch_vector_check.size(); i++){
           ClientItem ci = (ClientItem)ch_vector_check.elementAt(i);
           
            if (ci.gachds==ACTION_GDS_PENDING) {
                ci.gachds=ACTION_GDS_NOMAL;
                ci.deptStatus = result;
                updateStatus(ci.ma_tt);
                break;
            }
        }
    }

    public void switchForm(Displayable form){
        previousForm = currentform;
        currentform = form;
        display.setCurrent(form);
    }
    //-------------------------init all form------------------------------------
    private void initFormConfirm() {
        formConfirm = new Form("Gạch Nợ");

        fc_stringitem_content = new StringItem("", "Bạn muốn thoát ứng dụng!");
        fc_menu_cancel = new Command("Không", Command.CANCEL, 0);
        fc_menu_ok   = new Command("Có", Command.OK, 1);
        
        formConfirm.append(fc_stringitem_content);
        formConfirm.addCommand(fc_menu_cancel);
        formConfirm.addCommand(fc_menu_ok);
        formConfirm.setCommandListener(this); 
        
        switchForm(formConfirm);
    }
    
    private void initFormLuotGiao(String[] list, Displayable form) {
        dg_next_screen = form;
        formLuotGiao = new List("Chọn lượt giao", List.IMPLICIT);
        if (list.length>0){
            for (int i=0; i< list.length; i++){
                if (list[i].length()>0) {
                    formLuotGiao.append(list[i].trim(), null);
                    //String[] a = splitString(list[i], ":");
                    //if (a.length>=3)
                    //   formLuotGiao.append(a[0]+"_"+a[1]+"_"+a[3].substring(0, a[3].indexOf(" ")), null);
                }
            }
        }
        
        dg_menu_back = new Command("Trở về", Command.BACK, 0);
        dg_menu_ok   = new Command("Chọn", Command.OK, 1);
        
        formLuotGiao.addCommand(dg_menu_back);
        formLuotGiao.addCommand(dg_menu_ok);
        formLuotGiao.setCommandListener(this); 
        
        switchForm(formLuotGiao);
    }
    
    private void gdsInitForm() {
        formGachDS = new List(ch_formName, List.IMPLICIT);
        ch_vector_check = new Vector();
        
        ch_currentPage = 1;
        //ch_total_money = 0;
        //ch_total_check = 0;
        
        ch_menu_ok   = new Command("Gạch", Command.OK, 0);
        ch_menu_back = new Command("Trở về", Command.ITEM, 1);        
        ch_menu_next = new Command("Trang sau", Command.ITEM, 2);
        ch_menu_last = new Command("Trang trước", Command.ITEM, 3);
        ch_menu_check_page = new Command("Chọn hết trang", Command.ITEM, 4);
        ch_menu_check_all  = new Command("Chọn hết danh sách", Command.ITEM, 5);
        
        formGachDS.addCommand(ch_menu_back);
        formGachDS.addCommand(ch_menu_ok);
        formGachDS.addCommand(ch_menu_next);
        formGachDS.addCommand(ch_menu_last);
        formGachDS.addCommand(ch_menu_check_page);
        formGachDS.addCommand(ch_menu_check_all);
        formGachDS.setCommandListener(this); 
        //formGachDS.set
        
        switchForm(formGachDS);
        gdsCheckListClient(ACTION_GACH_DS_LOAD_LIST);    
    }
    
     public void initKqForm(){
        formGachDsKq = new Form(AppName);
        kq_string_total    = new StringItem("Tổng số phiếu: ", "");
        kq_string_success  = new StringItem("Gạch thành công: ", "");
        kq_string_fail     = new StringItem("Gạch nợ lỗi: ", "");
        kq_string_status   = new StringItem("Trạng thái: ", "");    
        kq_menu_cancel = new Command("Dừng", Command.OK, 0);
        formGachDsKq.append(kq_string_total);
        formGachDsKq.append(kq_string_success);
        formGachDsKq.append(kq_string_fail);
        formGachDsKq.append(kq_string_status);         
        formGachDsKq.addCommand(kq_menu_cancel);       
        formGachDsKq.setCommandListener(this);   
    }
     
    public void updateFormKq(int total, int success, int fail){
        if (formGachDsKq==null){
            initKqForm();
        }else{
            if (kq_menu_cancel.getLabel().endsWith("Trở về")){
                formGachDsKq.removeCommand(kq_menu_cancel);
                kq_menu_cancel = new Command("Dừng", Command.OK, 0);     
                formGachDsKq.addCommand(kq_menu_cancel);
            }
        }
        
        kq_string_total.setText(total+"");
        kq_string_success.setText(success+"");
        kq_string_fail.setText(fail+"");
        kq_string_status.setText("đang gạch ...");
        
        switchForm(formGachDsKq);
    }
    
    public void initLoginForm(){              
        formLogin = new Form(AppName);
        L_user_code = new TextField("Mã an toàn:", "123", 30, TextField.PASSWORD);
        L_phone_number = new TextField("Số điện thoại:", phoneNumber, 30, TextField.ANY);
        L_cancel = new Command("Thoát", Command.CANCEL, 2);
        L_login = new Command("Đăng nhập", Command.OK, 2);
        
        formLogin.append(L_user_code);
        formLogin.append(L_phone_number);
        formLogin.addCommand(L_cancel);
        formLogin.addCommand(L_login);
        formLogin.setCommandListener(this);
        switchForm(formLogin);
    }
    
    public void initSettingForm(){
        formSetting = new Form(AppName);

        S_oldpass = new TextField("Mã an toàn hiện tại:", "", 30, TextField.PASSWORD);
        S_newpass = new TextField("Mã an toàn mới:", "", 30, TextField.PASSWORD);
        S_retype  = new TextField("Nhập lại mã an toàn:", "", 30, TextField.PASSWORD);
        
        S_string_int    = new StringItem("Tổng download: ", S_total_in +" byte");
        S_string_out    = new StringItem("Tổng upload: ", S_total_out +" byte");

        S_string_imei    = new StringItem("Imei: ", getIMEI());
        S_string_imsi    = new StringItem("Imsi: ", getIMSI());
        
        S_menu_back     = new Command("Trở về", Command.ITEM, 1);
        S_menu_update   = new Command("Cập nhật", Command.ITEM, 2);
        S_menu_reset    = new Command("Xóa bộ đếm dữ liệu", Command.ITEM, 3);

        formSetting.append(S_oldpass);
        formSetting.append(S_newpass);
        formSetting.append(S_retype);
        formSetting.append(S_string_int);
        formSetting.append(S_string_out);
        formSetting.append(S_string_imei);
        formSetting.append(S_string_imsi);

        formSetting.addCommand(S_menu_back);
        formSetting.addCommand(S_menu_update);
        formSetting.addCommand(S_menu_reset);
        formSetting.setCommandListener(this);

        switchForm(formSetting);
    }
    /**
     * Form chinh
     */
    public void mainInitForm(){
        formMain = new List(AppName, List.IMPLICIT);
        Calendar cal = Calendar.getInstance();
        cal.setTime(R_dateDateField.getDate());
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        M_currentPage = 1;
        M_totalRecord = 0;
        
        String currentDate = format("%s/%s/%s", new String[]{day+"", month+"", year+""});
        formMain.setTitle(AppName+":"+currentDate );

        M_menu_exit     = new Command("Thoát", Command.CANCEL, 0);
        M_menu_next     = new Command("Trang sau", Command.ITEM, 1);
        M_menu_last     = new Command("Trang trước", Command.ITEM, 2);
        M_menu_dotgiao  = new Command("Chọn lượt giao", Command.ITEM, 3);
        M_menu_gachno_ds= new Command("Gạch danh sách", Command.ITEM, 4);
        M_truyvan       = new Command("Tra cứu khách hàng", Command.ITEM, 5);
        M_menu_report   = new Command("Xem báo cáo", Command.ITEM, 6);
        M_menu_setting  = new Command("Tùy chọn", Command.ITEM, 7);

        formMain.addCommand(M_menu_exit);
        formMain.addCommand(M_menu_next);
        formMain.addCommand(M_menu_last);
        formMain.addCommand(M_menu_dotgiao);
        formMain.addCommand(M_menu_gachno_ds);
        formMain.addCommand(M_menu_report);
        formMain.addCommand(M_menu_setting);
        formMain.addCommand(M_truyvan);
        formMain.setCommandListener(this); 
        
        startConnect(ACTION_CLIENT_LIST);             
        switchForm(formMain);
       // switchForm((Form)mainform);
    }
    /**
     * Cap nhat thong tin tren title main form
     */
    public String mainInitTitle(){
        int totalPage = M_totalRecord/M_recordPerPage;
        if (totalPage*M_recordPerPage<M_totalRecord){
            totalPage++;
        }
        return "GN_"+dg_luot_giao_id+"_"+M_totalRecord+"_" + M_currentPage+"/"+ totalPage;
    }
    
    public void initFormSearch(){
        if (formSearch==null){            
            formSearch = new Form(AppName);
            
            fs_textfield_mathanhtoan = new TextField("Mã thanh toán:", "", 30, TextField.ANY);
            fs_textfield_sodt = new TextField("Số điện thoại", "", 30, TextField.NUMERIC);
            
            fs_menu_back  = new Command("Trở ra", Command.CANCEL, 0);
            fs_menu_ok = new Command("Truy vấn", Command.OK, 1);
            
            formSearch.append(fs_textfield_mathanhtoan);
            formSearch.append(fs_textfield_sodt);
            
            formSearch.addCommand(fs_menu_back);
            formSearch.addCommand(fs_menu_ok);
            
            formSearch.setCommandListener(this);
        }
        switchForm(formSearch);
    }
    
    public void initClientForm(ClientItem infor){
        if (formClient==null){
            C_hdid = infor.id_hoadon;
            C_payId = infor.id_payment;
            formClient = new Form(AppName);
            if (infor!=null){
                C_string_cid    = new StringItem("Mã thanh toán: ", infor.ma_tt);
                C_string_seri   = new StringItem("Số seri: ", infor.so_seri);
                C_string_name   = new StringItem("Tên khách hàng: ", infor.ten_khachhang);
                C_string_sodt   = new StringItem("Số diện thoại: ", infor.so_dt);
                C_string_money  = new StringItem("Số tiền: ", toCurrency(infor.tong_tien) +" vnđ");
                C_string_status = new StringItem("Tình trạng: ", "Chưa thanh toán");

                C_menu_clear    = new Command("Gạch nợ", Command.OK, 1);

                formClient.append(C_string_cid);
                formClient.append(C_string_seri);
                formClient.append(C_string_name);
                formClient.append(C_string_sodt);
                formClient.append(C_string_money);
                formClient.append(C_string_status);
                formClient.addCommand(C_menu_clear);
            }
            C_menu_back  = new Command("Trở ra", Command.CANCEL, 0);
            formClient.addCommand(C_menu_back);
            formClient.setCommandListener(this);
        }else{
            if (infor!=null){
                C_hdid = infor.id_hoadon;
                C_payId = infor.id_payment;
                C_string_seri.setText(infor.so_seri);
                C_string_cid.setText(infor.ma_tt);
                C_string_name.setText(infor.ten_khachhang);
                C_string_sodt.setText(infor.so_dt);
                C_string_money.setText(toCurrency(infor.tong_tien));
                if(!infor.deptStatus) {
                    C_string_status.setText("Chưa thanh toán");
                }else {
                    C_string_status.setText("Đã thanh toán");
                }
            }else{
                C_string_cid.setText("");
                C_string_seri.setText("");
                C_string_name.setText("");
                C_string_sodt.setText("");
                C_string_money.setText("");
                C_string_status.setText("");
            }
        }
        switchForm(formClient);
    }
    
    public void hgnInitForm(ReportItem item){
        H_item = item;
        if (formHuyGachNo==null){
            //C_hdid = infor.id_hoadon;
            //C_payId = infor.id_payment;
            formHuyGachNo = new Form(AppName);
            if (item!=null){
                H_string_matt    = new StringItem("Mã thanh toán: ", item.ma_tt);    
                H_string_name    = new StringItem("Tên khách hàng: ", item.ten_khachhang);
                H_string_so_dt   = new StringItem("Số diện thoại: ", item.sodt);
                H_string_so_tien   = new StringItem("Số tiền: ", toCurrency(item.so_tien)+" vnđ");
                H_string_ngay_gach  = new StringItem("Ngày gạch: ", item.ngay_thanh_toan);
                H_string_trangthai = new StringItem("Tình trạng: ", "Đã thanh toán");
                
                H_menu_ok    = new Command("Hủy gạch nợ", Command.OK, 1);

                formHuyGachNo.append(H_string_matt);
                formHuyGachNo.append(H_string_name);
                formHuyGachNo.append(H_string_so_dt);
                formHuyGachNo.append(H_string_so_tien);
                formHuyGachNo.append(H_string_ngay_gach);
                formHuyGachNo.append(H_string_trangthai);
              
                formHuyGachNo.addCommand(H_menu_ok);
            }
            H_menu_back  = new Command("Trở ra", Command.CANCEL, 0);
            formHuyGachNo.addCommand(H_menu_back);
            formHuyGachNo.setCommandListener(this);
        }else{
            if (item!=null){
                H_string_name.setText(item.ten_khachhang);
                H_string_so_dt.setText(item.sodt);
                H_string_so_tien.setText(toCurrency(item.so_tien)+" vnđ");
                H_string_ngay_gach.setText(item.ngay_thanh_toan);
                if(!item.deptStatus) {H_string_trangthai.setText("Chưa thanh toán");}
                else {H_string_trangthai.setText("Đã thanh toán");}
            }else{
                H_string_name.setText("");
                H_string_so_dt.setText("");
                H_string_so_tien.setText("");
                H_string_ngay_gach.setText("");
                H_string_trangthai.setText("");
            }
        }
        switchForm(formHuyGachNo);
    }

    public void reportInitForm(String[] data, int type){
        if (type == 1){
            formReport.deleteAll();
            formReport = null;
        }

        if (formReport==null){
            formReport = new Form(AppName);  
            
            String[] show = new String[1];
            show[0] = "Không có thông tin";
            
            if (R_currentPage==1){
                R_totalRecord = Integer.parseInt(data[0].trim());
                R_totalMoney = data[1].substring("Total Money:".length()).trim();
            }          
                                
            if (data.length>=1){
                int startIndex = 0;
                //reportData = new String[data.length-3];
                if (R_currentPage==1) {
                    show = new String[data.length-2];
                    startIndex = 2;                   
                }else {
                    show = new String[data.length];
                }
                int count=0;
                listReport = new ReportItem[show.length];
                for (int i=startIndex; i<data.length; i++){
                    if (data[i].length()>10){
                        String[] a = splitString(data[i], ":");
                        if (a.length>=8) {
                            ReportItem r = new ReportItem(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
                            listReport[count] = r;
                            //show[count] = listReport[count].ten_khachhang + "    " + listReport[count].sodt;
                            show[count] = reportShowItem(listReport[count]);                           
                            count++;
                        }
                    }
                }
            }

            R_menu_back     = new Command("Trở ra", Command.CANCEL, 0);
            R_menu_next     = new Command("Trang sau", Command.ITEM, 1);
            R_menu_last     = new Command("Trang trước", Command.ITEM, 2);
            
            R_menu_ds_dot   = new Command("Xem theo lượt", Command.ITEM, 3);
            R_menu_search   = new Command("Tìm kiếm", Command.ITEM, 4);
            R_menu_huy      = new Command("Hủy gạch nợ", Command.ITEM, 5);
            R_menu_update   = new Command("Cập nhật", Command.ITEM, 6);
            R_menu_select   = new Command("Chọn", Command.OK, 7);

            //R_list = new List("Khách hàng", Choice.EXCLUSIVE);
            R_list = new ChoiceGroup("" , Choice.EXCLUSIVE, show, null);
            R_list.setDefaultCommand(R_menu_select);
            R_list.setItemCommandListener(this);
            
            reportUpdateListTitle();

            //reportform.append(R_string_date);
            formReport.append(R_dateDateField);
            formReport.append(R_list);

            formReport.addCommand(R_menu_back);
            formReport.addCommand(R_menu_next);
            formReport.addCommand(R_menu_last);
            formReport.addCommand(R_menu_ds_dot);
            formReport.addCommand(R_menu_search);
            formReport.addCommand(R_menu_huy);
            formReport.addCommand(R_menu_update);
            formReport.setCommandListener(this);
        }

        switchForm(formReport);
    }
    /*
     * Hien thi item cua report
     */
    public String reportShowItem(ReportItem ri){        
        return ri.ma_tt + "_" + ri.ten_khachhang + "_" +toCurrency(ri.so_tien)+"vnđ";
    }
    /**
     * Cap nhat noi dung title cua list trong form report
     */
    public void reportUpdateListTitle(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(R_dateDateField.getDate());
        String date = cal.get(Calendar.DAY_OF_MONTH) + "-" + ( cal.get(Calendar.MONTH) + 1 ) + "-" + cal.get(Calendar.YEAR);

        
        String sTemp = "";
        if (R_totalRecord>0){
            int totalPage = R_totalRecord/R_recordPerPage;
            if (totalPage*R_recordPerPage<R_totalRecord){
                totalPage++;
            }
            sTemp = R_currentPage+"/"+totalPage;
        }
            
        R_list.setLabel(date+"_"+sTemp+"_"+R_totalRecord+"_"+toCurrency(R_totalMoney)+"vnđ");
    }
    public void initReportDotForm(String[] data, int type){
        if (type == 1){
            formReportDot.deleteAll();
            formReportDot = null;
        }

        if (formReportDot==null){
            formReportDot = new Form(AppName);  
            
            String[] show = new String[1];
            show[0] = "Không có thông tin";
            
            if (Rd_currentPage==1){
                Rd_totalRecord = Integer.parseInt(data[0].trim());
                Rd_totalMoney = data[1].substring("Total Money:".length()).trim();
            }          
                                
            if (data.length>=1){
                int startIndex = 0;
                //reportData = new String[data.length-3];
                if (Rd_currentPage==1) {
                    show = new String[data.length-2];
                    startIndex = 2;                   
                }else {
                    show = new String[data.length];
                }
                int count=0;
                listReportDot = new ReportItem[show.length];
                for (int i=startIndex; i<data.length; i++){
                    if (data[i].length()>10){
                        String[] a = splitString(data[i], ":");
                        if (a.length>=8) {
                            ReportItem r = new ReportItem(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
                            listReportDot[count] = r;
                            //show[count] = listReportDot[count].ten_khachhang + "    " + listReportDot[count].sodt;
                            show[count] = reportShowItem( listReportDot[count]);
                            count++;
                        }
                    }
                }
            }
  
            Rd_menu_back     = new Command("Trở ra", Command.CANCEL, 0);
            Rd_menu_next     = new Command("Trang sau", Command.ITEM, 1);
            Rd_menu_last     = new Command("Trang trước", Command.ITEM, 2);
            
            //Rd_menu_huy      = new Command("Hủy gạch nợ", Command.ITEM, 4);
            //Rd_menu_update   = new Command("Cập nhật", Command.ITEM, 4);
            Rd_menu_select   = new Command("Chọn", Command.OK, 5);

            String sTemp = "";
            if (Rd_totalRecord>0){
                int totalPage = Rd_totalRecord/Rd_recordPerPage;
                if (totalPage*Rd_recordPerPage<Rd_totalRecord){
                    totalPage++;
                }
                sTemp = Rd_currentPage+"/"+totalPage;
            }
            //R_list = new List("Khách hàng", Choice.EXCLUSIVE);
            Rd_list = new ChoiceGroup(Rd_Date+" Tổng : "+ toCurrency(Rd_totalMoney)+" vnđ_"+Rd_totalRecord+" "+sTemp , Choice.EXCLUSIVE, show, null);
            Rd_list.setDefaultCommand(Rd_menu_select);
            Rd_list.setItemCommandListener(this);

            formReportDot.append(Rd_list);

            formReportDot.addCommand(Rd_menu_back);
            formReportDot.addCommand(Rd_menu_next);
            formReportDot.addCommand(Rd_menu_last);
            //formReportDot.addCommand(Rd_menu_huy);
            //formReportDot.addCommand(Rd_menu_update);
            formReportDot.setCommandListener(this);
        }

        switchForm(formReportDot);
    }
    /**
     * parse data vao mang
     * @param arr 
     */
    private void mainInitList(String[] arr) {
        
        if (formMain!=null) {
            formMain.deleteAll();
        }
        
        listClient = new ClientItem[arr.length];

        if (M_currentPage==1) {
            if (arr[0].length()<10)  {
                int t = Integer.parseInt(arr[0]);
                if (t>0) {
                    M_totalRecord=t;
                    if (M_totalRecord<=0) {return;}
                    listClient = new ClientItem[arr.length-1];
                    //formMain.setTitle("Lg:"+dg_luot_giao_id +"*"+ M_totalRecord +"_"); 
                    //formMain.setTitle(mainInitTitle());
                }
            }
        }
       
        int count = 0;
         for (int i=0; i<arr.length; i++){
             String[] a = splitString(arr[i], ":");
             if (a.length>=7){
                 ClientItem ci = new ClientItem(a[0], a[1], a[2], a[3], a[4],  a[5],  a[6]);
                 listClient[count]= ci;                
//                 formMain.append(   listClient[count].ten_khachhang +
//                                    "\r\nĐt:" + listClient[count].so_dt + 
//                                    "\r\nNợ:"+ toCurrency(listClient[count].tong_tien)+" vnđ", 
//                                    null);
                 formMain.append( initClientInfor( listClient[count],0), null);
                 count++;
             }
        }

        if (M_totalRecord>0){             
            formMain.setTitle(mainInitTitle());
        }
        switchForm(formMain);
    }
    /*
     * Hien thi noi dung list
     */
    private String initClientInfor(ClientItem lc, int type){
        return (lc.so_seri + "_" + lc.ma_tt +  "_"+ toCurrency(lc.tong_tien)+" vnđ");
    }
    
    /**
     * parse data vao mang
     * @param arr 
     */
    private void initGachDsList(String[] arr) {
        formGachDS.deleteAll();
        ch_listClient = new ClientItem[arr.length];
        if (arr.length>1) {
            if (arr[0].length()<10)  {
                int t = Integer.parseInt(arr[0]);
                if (t>0) {
                    ch_totalRecord=t;
                }
            }
        }
       
        int count = 0;
        for (int i=0; i<arr.length; i++){
            String[] a = splitString(arr[i], ":");
            if (a.length>=7){
                ClientItem ci = new ClientItem(a[0], a[1], a[2], a[3], a[4],  a[5],  a[6]);
                //listClient[count]= ci; 
                //kiem tra xem co trung gia tri khong?
                
                
                int k = checkInVector(ci);
                if (k>=0){
                    ClientItem item = (ClientItem)ch_vector_check.elementAt(k);
                    ch_listClient[count]=item;
                    if (item.gachds==ACTION_GDS_LIST){
                        formGachDS.append(initClientInfor(ci,0), check);
                    }else{
                        formGachDS.append(initClientInfor(ci,0), uncheck);
                    }
                }else{
                    ch_vector_check.addElement(ci);
                    ch_listClient[count]=ci;
                    formGachDS.append(initClientInfor(ci,0), uncheck);
                }
                //if (ch_vector_check.indexOf(ci)>=0){ 
                //    System.out.println("111:" + ci.ten_khachhang);
                //}else{
                //    ch_vector_check.addElement(ci);                  
                //}              
                
                count++;
            }
        }

        if (ch_totalRecord>=1){
            gdsUpdateTitle();
//            String s = formGachDS.getTitle();
//            String[] a = splitString(s, "_");
//
//            int totalPage = ch_totalRecord/ch_recordPerPage;
//            if (totalPage*ch_recordPerPage<ch_totalRecord){
//                totalPage++;
//            }
//            s = "_"+ch_currentPage+"/"+ totalPage + "~" + toCurrency(ch_total_money+"")+" vnđ";
//            formGachDS.setTitle(a[0] + s);
        }
            
        switchForm(formGachDS);
    }
    /**
     * Kiểm tra ci co trong vector khong, co thi cap nhat
     */
    private int checkInVector(ClientItem ci) {
        for (int i=0; i< ch_vector_check.size(); i++){
            ClientItem item = (ClientItem)ch_vector_check.elementAt(i);
            if (ci.ma_tt.equals(item.ma_tt)){
                return i;               
            }
        }
        return -1;
    }
    
    public void commandAction(Command c, Item item) {
        System.out.println("commandAction item");
        //throw new UnsupportedOperationException("Not supported yet.");
        if(c==M_menu_exit){
            destroyApp(true);
        }else if (c==M_menu_client){
            startConnect(ACTION_CLIENT_LIST);  
        }else if (c==M_menu_report){
            //initReportForm();
            if (nv_pass.length()<=0 || nv_id.length()<=0){
                showInfor(AppName, "Bạn cần nhập đầy đủ thông tin!", 2000, AlertType.WARNING);
            }else{
                startConnect(ACTION_REPORT_SETDAY);  
            }
        }else if (c == M_menu_setting){
            initSettingForm();
        }else if (c==R_menu_select){
            
            /*boolean get[] = new boolean[R_list.size()];
            R_list.getSelectedFlags(get);

            for (int i=0; i<get.length; i++){
                if (get[i]){
                    String[] a = splitString(reportData[i], "&&&");
                    showInfor(AppName, a[0] + "   "+a[1] +"   "+toCurrency(a[2])+ " vnđ", -1, AlertType.INFO);
                    break;
                }
            }*/
            
            
        }
    }

    public void commandAction(Command c, Displayable d) {
        System.out.println("commandAction");
        if (d==formLogin){
            if (c==L_login){
                if (L_user_code.getString().length()<=0 || L_phone_number.getString().length()<=0){
                    showInfor(AppName, "Bạn cần nhập đầy đủ thông tin!", 2000, AlertType.WARNING);
                }else {
                    saveSettingRMS(AppVerson);
                    startConnect(ACTION_LOGIN);
                }
            }else if (c==L_cancel){
                destroyApp(true);
            }
        }else if (d==formConfirm){
            if (c==fc_menu_cancel){
                switchForm(formMain); 
            }else if (c==fc_menu_ok){
                saveSettingRMS(AppVerson);
                destroyApp(true);
            }
        }else if (d==formMain){
            if(c==M_menu_exit){
                //destroyApp(true);
                initFormConfirm();
            }else if(c==M_menu_client){
                startConnect(ACTION_CLIENT_LIST);           
            }else if(c==M_menu_report){
                //initReportForm();
                
                /*if (nv_pass.length()<=0 || nv_id.length()<=0){
                    showInfor(AppName, "Bạn cần nhập đầy đủ thông tin!", 2000, AlertType.WARNING);
                }else{
                    startConnect(ACTION_REPORT_CURRENT);     
                }*/
                //startConnect(ACTION_LUOT_GIAO_REPORT); 
                startConnect(ACTION_REPORT_CURRENT);    
                
            }else if(c==M_menu_setting){
                initSettingForm();
            }else if (c==M_truyvan){
                initFormSearch();
            }else if (c==M_menu_next){
                //initGetInforForm();
                if ((M_totalRecord - M_currentPage*M_recordPerPage)>0){
                    M_currentPage++;
                    startConnect(ACTION_CLIENT_LIST);     
                }
            }else if (c==M_menu_last){
               if (M_currentPage>1) {
                    M_currentPage--;
                    startConnect(ACTION_CLIENT_LIST);     
               }else{
                   startConnect(ACTION_CLIENT_LIST);  
               }
            }else if(c==M_menu_dotgiao){
                startConnect(ACTION_LUOT_GIAO_MAIN);  
            }else if (c==M_menu_gachno_ds){
                gdsInitForm();
            }else{
                M_selectedIndex = formMain.getSelectedIndex();                              
                initClientForm(listClient[M_selectedIndex]);
            }
        }else if (d==formClient){
            if (c==C_menu_back){
                //tro ve
                switchForm(formMain);
                if (R_success) {
                    startConnect(ACTION_REPORT_SETDAY);
                }
            }else if (c==C_menu_clear){
                startConnect(ACTION_GACH_NO);     
            }
        }else if (d==formReport){
            if (c==R_menu_back){
                formReport.deleteAll();
                formReport = null;
                switchForm(formMain);
                R_currentPage = 1;
            }else if (c==R_menu_update){
                startConnect(ACTION_REPORT_SETDAY);     
            }else if (c==R_menu_next){
                if ((R_totalRecord - R_currentPage*R_recordPerPage)>0){
                    R_currentPage++;
                    startConnect(ACTION_REPORT_SETDAY);
                }
                
            }else if (c==R_menu_last){              
                if (R_currentPage>1){
                    R_currentPage--;
                    startConnect(ACTION_REPORT_SETDAY);
                }               
            }else if (c==R_menu_ds_dot){
                                /*if (nv_pass.length()<=0 || nv_id.length()<=0){
                    showInfor(AppName, "Bạn cần nhập đầy đủ thông tin!", 2000, AlertType.WARNING);
                }else{
                    startConnect(ACTION_REPORT_CURRENT);     
                }*/
                startConnect(ACTION_LUOT_GIAO_REPORT); 
            }else if (c==R_menu_huy){
                H_previousForm = formReport;
                int index = R_list.getSelectedIndex();
                if (index>=0) {
                    hgnInitForm(listReport[index]);
                }
            }else if (c==R_menu_search){
                H_previousForm = formReport;
                initFormSearch();
            }
        }else if (d==formReportDot){  
            if (c==Rd_menu_back){
                formReportDot.deleteAll();
                formReportDot = null;
                switchForm(formReport);  
                Rd_currentPage = 1;
            }else if (c==Rd_menu_next){
                if ((Rd_totalRecord - Rd_currentPage*Rd_recordPerPage)>0){
                    Rd_currentPage++;
                    formReportDot.deleteAll();
                    formReportDot = null;
                    startConnect(ACTION_REPORT_DOTGIAO);
                }
                
            }else if (c==Rd_menu_last){              
                if (Rd_currentPage>1){
                    Rd_currentPage--;
                    formReportDot.deleteAll();
                    formReportDot = null;
                    startConnect(ACTION_REPORT_DOTGIAO);
                }               
            }else if (c==R_menu_search){
                H_previousForm = formReportDot;
                initFormSearch();
            }
        }else if (d==formSetting){
            if (c==S_menu_back){
                switchForm(formMain);
            }else if (c==S_menu_reset){
                S_total_in = 0;
                S_total_out = 0;
                S_string_int.setText(S_total_in +" byte");
                S_string_out.setText(S_total_out +" byte");
                
            }else if (c==S_menu_update){
                if ( (S_oldpass.getString().length()<=0)||(S_newpass.getString().length()<=0) ||(S_retype.getString().length()<=0)){
                    showInfor(AppName, "Cần nhập đầy đủ thông tin!", 2000, AlertType.WARNING);
                }else if (!S_oldpass.getString().equals(nv_pass)){
                    showInfor(AppName, "Mât khẩu cũ sai!", 2000, AlertType.WARNING);
                }else{
                    if (!S_newpass.getString().equals(S_retype.getString())){
                        showInfor(AppName, "Mât khẩu mới không giống nhau!", 2000, AlertType.WARNING);
                    }else{
                        startConnect(ACTION_PASS_CHANGE);     
                    }
                }                
            }
        }else if (d==formSearch){
            if (c==fs_menu_back){
                if (previousForm==formMain) {
                    switchForm(formMain);
                }else {
                    switchForm(formReport);
                }
            }else if (c==fs_menu_ok){
                if (fs_textfield_mathanhtoan.getString().length()<=0 && fs_textfield_sodt.getString().length()<=0){
                    showInfor(AppName, "Bạn cần nhập thộng tin!", 2000, AlertType.WARNING);
                }else{                
                    M_selectedIndex = -1;
                    if (previousForm==formMain){
                        startConnect(ACTION_SEARCH_LIST);
                    }else{
                        startConnect(ACTION_REPORT_SEARCH);
                    }
                }
            }
        }else if (d==formGachDS){
            if (c==ch_menu_back){
                switchForm(formMain);
            }else if (c==ch_menu_ok){
                startGachDs();
                //startConnect(ACTION_CLIENT_SEARCH);                
            }else if (c==ch_menu_next){
                if ((ch_totalRecord - ch_currentPage*ch_recordPerPage)>0){
                    ch_currentPage++;
                    gdsCheckListClient(ACTION_GACH_DS_LOAD_LIST);    
                }
            }else if (c==ch_menu_last){
               if (ch_currentPage>1) {
                    ch_currentPage--;
               }
               gdsCheckListClient(ACTION_GACH_DS_LOAD_LIST);                         
            }else if (c==ch_menu_check_page){
                
                if (ch_menu_check_page.getLabel().equals("Chọn hết trang")){
                    for (int i=0; i<formGachDS.size(); i++){
                        gdsCheckOneItem(i, 1);
                    }
                    formGachDS.removeCommand(ch_menu_check_page);
                    ch_menu_check_page = new Command("Bỏ chọn trang", Command.ITEM, 4);
                    formGachDS.addCommand(ch_menu_check_page);                           
                }else if (ch_menu_check_page.getLabel().equals("Bỏ chọn trang")){
                    for (int i=0; i<formGachDS.size(); i++){
                        gdsCheckOneItem(i, 2);
                    }
                    formGachDS.removeCommand(ch_menu_check_page);
                    ch_menu_check_page = new Command("Chọn hết trang", Command.ITEM, 4);
                    formGachDS.addCommand(ch_menu_check_page); 
                }
                gdsUpdateTitle();
            }else if (c==ch_menu_check_all){
                 //startConnect(ACTION_ALL_LIST_CLIEN);   
                 //checkListClient(ACTION_ALL_LIST_CLIEN); 
                if (ch_menu_check_all.getLabel().equals("Chọn hết danh sách")){
                    formGachDS.removeCommand(ch_menu_check_all);
                    ch_menu_check_all = new Command("Bỏ chọn danh sách", Command.ITEM, 5);
                    formGachDS.addCommand(ch_menu_check_all);                           
                }else if (ch_menu_check_all.getLabel().equals("Bỏ chọn danh sách")){
                    formGachDS.removeCommand(ch_menu_check_all);
                    ch_menu_check_all = new Command("Chọn hết danh sách", Command.ITEM, 5);
                    formGachDS.addCommand(ch_menu_check_all); 
                }                 
                gdsCheckListClient(ACTION_ALL_LIST_CLIEN); 
            }else{
                //item click
                //System.out.println("123");
                
                int index = formGachDS.getSelectedIndex();
                gdsCheckOneItem(index,0);
                gdsUpdateTitle();
//                String content = formGachDS.getString(index);
//                
//                formGachDS.delete(index);
//                
//                ClientItem item = ch_listClient[index];//(ClientItem)ch_vector_check.elementAt(index);
//                
//                //System.out.println("item:" + item.ten_khachhang);
//                if (item.gachds==ACTION_GDS_NOMAL){
//                    formGachDS.insert(index, content, check);
//                    item.gachds = ACTION_GDS_LIST;
//                    ch_total_money += Integer.parseInt(item.tong_tien);
//                }else{
//                    formGachDS.insert(index, content, uncheck);
//                    item.gachds = ACTION_GDS_NOMAL;
//                    ch_total_money -= Integer.parseInt(item.tong_tien);                    
//                }                
//                
//                String s = formGachDS.getTitle();
//                String[] a = splitString(s, "~");
//                formGachDS.setTitle(a[0] +"~" +toCurrency(ch_total_money+"") +" vnđ"); 
           }
            
        }else if (d==formLuotGiao){
            
            if (c==dg_menu_back){
                switchForm(formMain);
            }else {
                int i = formLuotGiao.getSelectedIndex();
                String s = formLuotGiao.getString(i);  
                String[] a = splitString(s, ":");
                if (a.length>=3){
                    dg_luot_giao_id = a[1];
                    Rd_Date = a[3];//a[3].substring(0, a[3].indexOf(" ")); 
                    
                    if (dg_next_screen == formMain) {
                        //startConnect(ACTION_CLIENT_LIST);
                        mainInitForm();
                    }else if (dg_next_screen== formReport){
                        startConnect(ACTION_REPORT_DOTGIAO);
                    }                    
                }
            }  
        }else if (d==formGachDsKq){
             if (c.getLabel().endsWith("Trở về")){
                switchForm(formMain);
             }else if (c.getLabel().endsWith("Dừng")){
                kq_menu_status = false;
             }
        }else if (d==formHuyGachNo){
            if (c==H_menu_back){
                switchForm(H_previousForm);
            }else if (c==H_menu_ok){
                System.out.println(H_item.ngay_thanh_toan+":"+H_item.ngay_hien_tai);
                if (H_item.ngay_thanh_toan.trim().equals(H_item.ngay_hien_tai.trim())){
                    startConnect(ACTION_HUY_GACH_NO);
                }else{
                    showInfor(AppName, "Chỉ hủy được phiếu trong ngày hiện tại!", 2000, AlertType.WARNING);
                }
            }
        }
    }
    /**
     * Kiem tra xem trong vector kh co chua, chua cho thi load tu server
     */
    public void gdsCheckListClient(int action){

        int size = ch_vector_check.size();
        //int maxPosLoad = (ch_currentPage-1)*ch_recordPerPage + (ch_recordPerPage-1);
        int maxPosLoad = ch_currentPage*ch_recordPerPage;
        if (action == ACTION_ALL_LIST_CLIEN){
            maxPosLoad = ch_totalRecord;
        }
        //System.out.println("MAxsizeload:" + maxSizeLoad);
        if (size<maxPosLoad) {
            startConnect(action);
        }else{
            System.out.println("Back");
            formGachDS.deleteAll();
            //if (ch_currentPage==1) ch_listClient = new ClientItem[ch_recordPerPage-1];
            //else 
            ch_listClient = new ClientItem[ch_recordPerPage];
            
            int count = 0;
            for (int i=(maxPosLoad-ch_recordPerPage); i<maxPosLoad; i++){
                if (i>=0){
                    ClientItem item = (ClientItem)ch_vector_check.elementAt(i);
                    ch_listClient[count]=item;
                    count++;
                    if (item.gachds==ACTION_GDS_LIST){
                        formGachDS.append(initClientInfor(item,0), check);
                    }else{
                        formGachDS.append(initClientInfor(item,0), uncheck);
                    }
                }
            }
                    
            if (ch_totalRecord>=1){
                gdsUpdateTitle();
//                String s = formGachDS.getTitle();
//                String[] a = splitString(s, "_");
//
//                int totalPage = ch_totalRecord/ch_recordPerPage;
//                if (totalPage*ch_recordPerPage<ch_totalRecord){
//                    totalPage++;
//                }
//                s = "_"+ch_currentPage+"/"+ totalPage + "~" + toCurrency(ch_total_money+"")+" vnđ";
//                formGachDS.setTitle(a[0] + s);
            }  
            if (action == ACTION_ALL_LIST_CLIEN){
                gdsUpdateCheckAll();
            }            
        }
    }
    /**
     * Cap nhat danh sach gach het
     */
    public void gdsUpdateCheckAll(){
        if (ch_menu_check_all.getLabel().equals("Chọn hết danh sách")){
            for (int i=0; i<ch_vector_check.size(); i++){
                ((ClientItem)ch_vector_check.elementAt(i)).gachds=ACTION_GDS_NOMAL;            
            }    
            for (int i=0; i<formGachDS.size(); i++){
                gdsCheckOneItem(i, 2);
            }
        }else if (ch_menu_check_all.getLabel().equals("Bỏ chọn danh sách")){
            for (int i=0; i<ch_vector_check.size(); i++){
                ((ClientItem)ch_vector_check.elementAt(i)).gachds=ACTION_GDS_LIST;            
            } 
            for (int i=0; i<formGachDS.size(); i++){
                gdsCheckOneItem(i, 1);
            }
        }
        gdsUpdateTitle();
    }
    
    /**
     * Cap nhat title cua form gach danh sach
     * @param formName: Ten Form
     * @param checkCount: tong so kh da chon
     * @param page: trang man hinh
     */
    private void gdsUpdateTitle(){
        int total = 0;
        int checkCl = 0;
        for (int i=0; i<ch_vector_check.size(); i++){
            ClientItem ci = (ClientItem)ch_vector_check.elementAt(i);            
            if (ci.gachds==ACTION_GDS_LIST) {
                checkCl++;
                total += Integer.parseInt(ci.tong_tien);
            }
        }
        int totalPage = ch_totalRecord/ch_recordPerPage;
        if (totalPage*ch_recordPerPage<ch_totalRecord){
            totalPage++;
        }
        formGachDS.setTitle(ch_formName + "_" + ch_currentPage+"/"+ totalPage + "_" + checkCl + "_"+toCurrency(total+"")+"vnđ");
    }
    /**
     * check 1 item trong form gach danh sach
     * @param index: vi tri trong list
     * @param type : 0: nomal; 1: check all; 2: uncheck all
     */
    public void gdsCheckOneItem(int index, int type){
        
        String content = formGachDS.getString(index);
        formGachDS.delete(index);
        
        ClientItem item = ch_listClient[index];//(ClientItem)ch_vector_check.elementAt(index);
        //System.out.println("item:" + item.ten_khachhang);
        if (type==0){
            if (item.gachds==ACTION_GDS_NOMAL){
                formGachDS.insert(index, content, check);
                item.gachds = ACTION_GDS_LIST;
                //ch_total_money += Integer.parseInt(item.tong_tien);
            }else{
                formGachDS.insert(index, content, uncheck);
                item.gachds = ACTION_GDS_NOMAL;
                //ch_total_money -= Integer.parseInt(item.tong_tien);                    
            }      
        }else if (type==1){
            if (item.gachds==ACTION_GDS_NOMAL){
                formGachDS.insert(index, content, check);
                item.gachds = ACTION_GDS_LIST;
                //ch_total_money += Integer.parseInt(item.tong_tien);
            }else if (item.gachds==ACTION_GDS_LIST){
                formGachDS.insert(index, content, check);  
            } 
        }else if (type==2){
            if (item.gachds==ACTION_GDS_NOMAL){
                formGachDS.insert(index, content, uncheck);
            }else if (item.gachds==ACTION_GDS_LIST){
                formGachDS.insert(index, content, uncheck);
                item.gachds = ACTION_GDS_NOMAL;
                //ch_total_money -= Integer.parseInt(item.tong_tien);    
            } 
        }

        //String s = formGachDS.getTitle();
        //String[] a = splitString(s, "~");
        //formGachDS.setTitle(a[0] +"~" +toCurrency(ch_total_money+"") +" vnđ"); 
    }
    /**
     * Hàm connect du lieu chinh
     * @param connectType 
     */
    public void startConnect(int type){
        connectType = type;
        switch (type){
            case ACTION_LOGIN:
                link = format(LINK_LOGIN, new String[]{L_user_code.getString(),L_phone_number.getString()});
                break;
            case ACTION_SEARCH_LIST:                             
                link = format(LINK_SEARCH_LIST, new String[]{mid, fs_textfield_mathanhtoan.getString(), fs_textfield_sodt.getString()});               
                break;
            case ACTION_REPORT_CURRENT:
                link = format(LINK_REPORT, new String[]{mid,R_currentPage+"", R_recordPerPage+"", getDDMMYYYY(M_dateDateField.getDate()), nv_pass});
                //link = format(LINK_REPORT, new String[]{mid, dg_luot_giao_id, R_currentPage+"", R_recordPerPage+""});//getDDMMYYYY(M_dateDateField.getDate())
                break;
            case ACTION_REPORT_SETDAY:
                //link = format(LINK_REPORT, new String[]{"1394","1394", getYYYMMDD(R_dateDateField.getDate())});
                link = format(LINK_REPORT, new String[]{mid,R_currentPage+"", R_recordPerPage+"", getDDMMYYYY(R_dateDateField.getDate()), nv_pass});
                break;
            case ACTION_REPORT_DOTGIAO:                
                link = format(LINK_REPORT_DOT, new String[]{mid, dg_luot_giao_id, Rd_currentPage+"", Rd_recordPerPage+""});
                break;    
            case ACTION_CLIENT_LIST:
                link = format(LINK_CLIENT_LIST, new String[]{mid, M_currentPage+"", M_recordPerPage+"", dg_luot_giao_id});
                break;                
            case ACTION_GACH_NO:   
                if (C_hdid.length()>0 && C_payId.length()>0){
                    link = format(LINK_GACHNO, new String[]{ nv_pass, C_hdid, C_payId, mid});     
                    C_hdid="";
                    C_payId="";
                }           
                break;   
            case ACTION_PASS_CHANGE:
                link = format(LINK_PASS_CHANGE, new String[]{ S_newpass.getString(), mid});
                break;   
            case ACTION_LUOT_GIAO_REPORT:
                link = format(LINK_LUOT_GIAO, new String[]{mid});
                break;  
           case ACTION_LUOT_GIAO_MAIN:
                link = format(LINK_LUOT_GIAO, new String[]{mid});
                break; 
           case ACTION_GACH_DS:
               int index = -1;
                ClientItem ci = null;
                for (int i=0; i< ch_vector_check.size(); i++){
                    ci = (ClientItem)ch_vector_check.elementAt(i);
                    if (ci.gachds==ACTION_GDS_LIST){
                        index = i;
                        break;
                    }
                }
                if (index>-1){
                    link = format(LINK_GACHNO, new String[]{ nv_pass, ci.id_hoadon.trim(), ci.id_payment.trim(), mid});  
                    ci.gachds = ACTION_GDS_PENDING;
                }
                break;
           case ACTION_HUY_GACH_NO:
                R_success = false;
                link = format(LINK_HUY_GACHNO, new String[]{H_item.phieutra, H_item.nguoigachid});
                break;
            case ACTION_REPORT_SEARCH:
                link = format(LINK_REPORT_SEARCH, new String[]{mid, fs_textfield_mathanhtoan.getString(), fs_textfield_sodt.getString()});//String[]{mid, fs_textfield_mathanhtoan.getString(), fs_textfield_sodt.getString()});
                break;
            case ACTION_GACH_DS_LOAD_LIST:
                link = format(LINK_CLIENT_LIST, new String[]{mid, ch_currentPage+"", ch_recordPerPage+"", dg_luot_giao_id});
                break;  
            case ACTION_ALL_LIST_CLIEN:
                link = format(LINK_CLIENT_LIST, new String[]{mid, "1", ch_totalRecord+"", dg_luot_giao_id});
                break;                 
            default:
                break;
        }
        System.out.println("StartConnect: "+link);
        new Thread( this ).start();
    }

    //connect---------------------------------------------------
    public void startConnect() {
        //throw new UnsupportedOperationException("Not supported yet.");
        if (connectType!=ACTION_GACH_DS) {
            showInfor("Đang kết nối","Xin chờ trong giây lát!", -1, AlertType.INFO);
        }
    }

    public void stopConnect(String result) {
        S_total_in += result.toCharArray().length;
        alertInfor.setTimeout(1);
        result = result.trim(); 
        
        if (result.indexOf("<br/>")==0) {
            result = result.substring("<br/>".length());
        }
        if (result.length() > "<br/>".length()){
            String s = result.substring(result.length() - "<br/>".length());
            if (s.equals("<br/>")) {
                result = result.substring(0, result.length() - "<br/>".length());
            }
        }
        System.out.println("Connect result:"+result);  
            
        switch (connectType) {
        case ACTION_LOGIN: 
            if (result.equals("0")){
                showInfor(AppName, "Sai thông tin đăng nhập!", 2000, AlertType.ERROR);
            }else{
                 nv_pass = L_user_code.getString();
                 nv_id   = L_phone_number.getString();
                 mid     = result;
                 startConnect(ACTION_LUOT_GIAO_MAIN);
                 //123initMainForm();
            }
            break;
        case ACTION_SEARCH_LIST: 
            if (result.length()==0){
                showInfor(AppName, "Không tìm thấy!", 2000, AlertType.ERROR);
            }else{
                String[] a = splitString(result, ":");
                if (a.length>=7){
                    ClientItem ci = new ClientItem(a[0], a[1], a[2], a[3], a[4],  a[5],  a[6]);
                    initClientForm(ci);
                }                
            }
            break;
        case ACTION_REPORT_CURRENT:               
            String[] arr = splitString(result, "<br/>");   
            //System.out.println("Result3 :"+arr.length);    
            if (arr.length>=1){
                reportInitForm(arr, 0);
            }else{
               showInfor(AppName, "Không có thông tin!", 2000, AlertType.ERROR);
               reportInitForm(arr, 0);
            }  
            break;
        case ACTION_REPORT_DOTGIAO:             
            arr = splitString(result, "<br/>");            
            if (arr.length>=1){
                initReportDotForm(arr, 0);
            }else{
               showInfor(AppName, "Không có thông tin!", 2000, AlertType.ERROR);
               initReportDotForm(arr, 0);
            } 
            
            break;     
        case ACTION_REPORT_SETDAY: 
            //up date report
            arr = splitString(result, "<br/>");
            if (arr.length>=1){
                reportInitForm(arr, 1);               
            }else{               
                showInfor(AppName, "Không có thông tin!", 2000, AlertType.ERROR);
            }  
            break;
        case ACTION_CLIENT_LIST: 
            arr = splitString(result, "<br/>");
            if (arr.length>1){
                mainInitList(arr);
                
            }else{
               showInfor(AppName, "Không có thông tin!", 2000, AlertType.ERROR);
            }
            break;  
            
        case ACTION_GACH_NO:    
            if (result.indexOf("1")>=0)//success
            {
                showInfor(AppName, "Gạch nợ thành công!", -1, AlertType.INFO);
                C_string_status.setText("Đã gạch nợ");
                updateStatus(C_string_cid.getText());
                //switchForm(mainform); 
            }else{
                showInfor(AppName, "Gạch nợ thất bại, hoặc đã gạch!", -1, AlertType.ERROR);
                C_string_status.setText("Gạch nợ thất bại, hoặc đã gạch");
            }
            return;                 
        case ACTION_PASS_CHANGE:     
            if (result.indexOf("true")>=0)//success
            {
                showInfor(AppName, "Đổi mã an toàn thành công!", 2000, AlertType.INFO);
                switchForm(formMain); 
            }else{
                showInfor(AppName, "Đổi mã an toàn thất bại!", 2000, AlertType.ERROR);
            }
            break;     
        case ACTION_LUOT_GIAO_REPORT: 
            String[] a = splitString(result, "<br/>");
            
            if (a.length>0){
                initFormLuotGiao(a, formReport);
                switchForm(formLuotGiao); 
            }
            
            break;  
        case ACTION_LUOT_GIAO_MAIN: 
            a = splitString(result, "<br/>");
            
            if (a.length>0){
                initFormLuotGiao(a, formMain);
                //switchForm(formLuotGiao); 
            }
            
            break;            
        case ACTION_GACH_DS: 
            if (result.indexOf("1")>=0)//success
            {   
                ch_sucess++;
                updateStatusDs(true);
            }else{
                ch_fail++;
                updateStatusDs(false);
            }
            //System.out.println((ch_sucess+ch_fail)+" :"+ch_total);
            updateFormKq(ch_total, ch_sucess, ch_fail);
            //int totalTime = -1;
            if ((ch_sucess+ch_fail)>=ch_total){
                kq_string_status.setText("đã gạch xong!"); 
                formGachDsKq.removeCommand(kq_menu_cancel);
                kq_menu_cancel = new Command("Trở về", Command.OK, 0);     
                formGachDsKq.addCommand(kq_menu_cancel);
            }else  {
                if (kq_menu_status) {
                    startConnect(ACTION_GACH_DS);
                }else{
                    formGachDsKq.removeCommand(kq_menu_cancel);
                    kq_menu_cancel = new Command("Trở về", Command.OK, 0);     
                    formGachDsKq.addCommand(kq_menu_cancel);
                }
            }
            return;  
        case ACTION_HUY_GACH_NO:
            if (result.equals("1")){
                H_string_trangthai.setText("Chưa thanh toán");
                showInfor(AppName, "Hủy thành công!", 2000, AlertType.INFO);
                updateReportList(H_item.ma_tt);
                R_currentPage = 1;
                R_success = true;
                startConnect(ACTION_REPORT_SETDAY);
            }else{
                showInfor(AppName, "Hủy thất bại!", 2000, AlertType.ERROR);
            }

            return;
        case ACTION_REPORT_SEARCH:
            a = splitString(result, ":");
            if (a.length>=8){
                ReportItem r = new ReportItem(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
                hgnInitForm(r);
            }else{
                showInfor(AppName, "Không tìm thấy!", 2000, AlertType.ERROR);
            }

            return;
        case ACTION_GACH_DS_LOAD_LIST: 
            arr = splitString(result, "<br/>");
            if (arr.length>1){
                initGachDsList(arr);
            }else{
               showInfor(AppName, "Không có thông tin!", 2000, AlertType.ERROR);
            }
            break;   
        case ACTION_ALL_LIST_CLIEN:
            arr = splitString(result, "<br/>");
            if (arr.length>1){
                initAllClient(arr);
            }else{
               showInfor(AppName, "Không có thông tin!", 2000, AlertType.ERROR);
            }
            gdsUpdateCheckAll();
            break;
        default:
            break;
        }
    }
    
    private void initAllClient(String[] arr) {
        for (int i=0; i<arr.length; i++){
            String[] a = splitString(arr[i], ":");
            if (a.length>=7){
                ClientItem ci = new ClientItem(a[0], a[1], a[2], a[3], a[4],  a[5],  a[6]);              
                if (checkInVector(ci)<0) {
                    ch_vector_check.addElement(ci);
                }
            }
        }  

    }
    
    public void httpError(String error) {
        //throw new UnsupportedOperationException("Not supported yet.");
        showInfor("Lỗi kết nối","Xin kiểm tra lại kết nối Internet!", -1, AlertType.ERROR);
    }    
    //--------------------------------------------------------------------------
    /**
     * doi string sang dang tien te
     * @param s
     * @return 
     */
    public String toCurrency(String s){
        String result = "";
        int count =1;
        for (int i=s.length()-1; i>=0; i--){
            result=s.charAt(i)+result;
            //if (i!=0 && (s.length()-i)%3==0) result = "."+result;
            if (count==3){
                result = "."+result;
                count = 0;
            }
            count++;
        }
        if (result.charAt(0)=='.'){
            result= result.substring(1);
        }
        return result;
    }
    /**
     * Cat chuoi thanh mang
     * @param Source
     * @param Delimiter
     * @return 
     */    
    public static String[] splitString(String Source, String Delimiter) {
        int iCount, iPos, iLength;
        boolean bEnd;
        String sTemp;
        String[] aSplit = null, t = null;

        sTemp = Source;
        iCount = 0;
        iLength = Delimiter.length();
        bEnd=sTemp.endsWith(Delimiter);

        for (; ; ) {
            iPos = sTemp.indexOf(Delimiter);
            if (iPos < 0) {
                break;
            }
            else {
                if (iCount > 0) {
                    t = aSplit;
                }
                iCount++;
                aSplit = new String[iCount];
                if (iCount > 1) {
                    //for (int i = 0; i < t.length; i++) {
                    //    aSplit[i] = t[i];
                    //}
                    System.arraycopy(t, 0, aSplit, 0, t.length);
                }
                aSplit[iCount - 1] = sTemp.substring(0, iPos);
                sTemp = sTemp.substring(iPos + iLength);
            }
        }

        if( (sTemp.length() >= 0) || bEnd) {
            if (iCount > 0) {
                t = aSplit;
            }
            iCount++;
            aSplit = new String[iCount];
            if (iCount > 1) {
                for (int i = 0; i < t.length; i++) {
                    aSplit[i] = t[i];
                }
            }
            aSplit[iCount - 1] = sTemp;
        }
        return aSplit;
    }
    
    /**
     * String.format ("Your name is %s and you are %s years old", "Mark", "18");
     * @param format
     * @param args
     * @return
     */
    public static String format(String format, String[] args) {
        int argIndex = 0;
        int startOffset = 0;
        int placeholderOffset = format.indexOf("%s");

        if (placeholderOffset == -1) {
            return format;
        }

        int capacity = format.length();

        if (args != null) {
            for (int i=0;i<args.length;i++) {
                capacity+=args[i].length();
            }
        }

        StringBuffer sb = new StringBuffer(capacity);

        while (placeholderOffset != -1) {
            sb.append(format.substring(startOffset,placeholderOffset));

            if (args!=null && argIndex<args.length) {
                sb.append(args[argIndex]);
            }

            argIndex++;
            startOffset=placeholderOffset+2;
            placeholderOffset = format.indexOf("%s", startOffset);
        }

        if (startOffset<format.length()) {
            sb.append(format.substring(startOffset));
        }

        return sb.toString();
    }       
    /**
     * showInfor
     * @param title
     * @param content
     * @param time
     * @param A 
     */
    public void showInfor(String title, String content, int time, AlertType A) {  
      //Alert error = new Alert("Login Incorrect", "Please try again", imge, AlertType.ERROR);
      alertInfor = new Alert(title, content, null, A);
      if (time == -1) {
          alertInfor.setTimeout(Alert.FOREVER);
      }
      else {
          alertInfor.setTimeout(time);
      }
      display.setCurrent(alertInfor, currentform);
    }        
    
    public String getDateString(){
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        String currentDate = year +"";
        if (month<10) {
            currentDate +="0"+month;
        }
        else {
            currentDate +=month;
        }
        if (day<10) {
            currentDate +="0"+day;
        }
        else {
            currentDate +=day;
        }
        return currentDate;
    }

    public String getYYYMMDD(Date d){
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        String result = year +"";
        if (month<10) {
            result +="0"+month;
        }
        else {
            result +=month;
        }

        if (day<10) {
            result +="0"+day;
        }
        else {
            result +=day;
        }
        return result;
    }
    
    public String getDDMMYYYY(Date d){
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);

        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);

        String result = "";
        if (day<10) {
            result +="0"+day;
        }
        else {
            result +=day;
        }

        if (month<10) {
            result +="/0"+month;
        }
        else {
            result +="/"+month;
        }
        result +="/"+year;
        return result;
    }
    //-----------------------RMS------------------------------------------------
    public void saveSettingRMS(String name) {
        phoneNumber = L_phone_number.getString();
        try {
            //byte status[] = {(byte)nThemes, (byte)nCharSets, (byte)curScenario, (byte)kqbangForm.nBang, (byte)nhaptisoForm.nTran};
            //System.out.println(nThemes + ""+ nCharSets);
            RecordStore rs = RecordStore.openRecordStore(name, true);
            if (rs.getNumRecords() == 0) {
                //rs.addRecord(status, 0, status.length);
                rs.addRecord(phoneNumber.getBytes(), 0, phoneNumber.getBytes().length); 
                rs.addRecord((S_total_in+"").getBytes(), 0, (S_total_in+"").getBytes().length);
                rs.addRecord((S_total_out+"").getBytes(), 0, (S_total_out+"").getBytes().length);
            } else {
                //rs.setRecord(1, status, 0, status.length);
                rs.setRecord(1, phoneNumber.getBytes(), 0, phoneNumber.getBytes().length);
                rs.setRecord(2, (S_total_in+"").getBytes(), 0, (S_total_in+"").getBytes().length);
                rs.setRecord(3, (S_total_out+"").getBytes(), 0, (S_total_out+"").getBytes().length);
            }
            System.out.println("save rms:"+S_total_in);
        } catch(RecordStoreException re) { }  
    }
    //--------------------------------------------------------------------------
    public void readSettingRMS(String name) {        
        try {
            RecordStore rs = RecordStore.openRecordStore(name, true);
            if (rs.getNumRecords() != 0) {
                    /*if (rs.getRecord(1) != null){			
                        byte status[] = rs.getRecord(1); 
                        nThemes   = status[0];
                        nCharSets = status[1];
                        curScenario = status[2];
                        nBang = status[3];
                        nTran = status[4];                       
                    }*/
                    if (rs.getRecord(1) != null){
                        phoneNumber = new String(rs.getRecord(1));
                    }
                    if (rs.getRecord(2) != null){
                        S_total_in =  Integer.parseInt(new String(rs.getRecord(2)));
                    }else S_total_in = 0;
                    
                    if (rs.getRecord(3) != null){
                        S_total_out =  Integer.parseInt(new String(rs.getRecord(3)));
                    }else S_total_out = 0;
                    
                    System.out.println("Read rms: "+S_total_in);
            }
            rs.closeRecordStore();
        } catch(RecordStoreException re) {
            phoneNumber = "";
        }             
    }    
    public String getIMEI() {
	String out = "";
	try {
		out = System.getProperty("com.imei");
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("phone.imei");
		}
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("com.nokia.IMEI");
		}
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("com.nokia.mid.imei");
		}
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("com.sonyericsson.imei");
		}
 
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("IMEI");
		}
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("com.motorola.IMEI");
		}
 
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("com.samsung.imei");
		}
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("com.siemens.imei");
		}
 
		if (out == null || out.equals("null") || out.equals("")) {
			out = System.getProperty("imei");
		}
 
	} catch (Exception e) {
		return out == null ? "" : out;
	}
	return out == null ? "" : out;
    }
    //code for getting IMSI of the phone
    public String getIMSI() {
            String out = "";
            try {
                    out = System.getProperty("IMSI");
                    if (out == null || out.equals("null") || out.equals("")) {
                            out = System.getProperty("phone.imsi");
                    }
                    if (out == null || out.equals("null") || out.equals("")) {
                            out = System.getProperty("com.nokia.mid.mobinfo.IMSI");
                    }
                    if (out == null || out.equals("null") || out.equals("")) {
                            out = System.getProperty("com.nokia.mid.imsi");
                    }
                    if (out == null || out.equals("null") || out.equals("")) {
                            out = System.getProperty("IMSI");
                    }
                    if (out == null || out.equals("null") || out.equals("")) {
                            out = System.getProperty("imsi");
                    }
            } catch (Exception e) {
                    return out == null ? "" : out;
            }
            return out == null ? "" : out;
    }
}
